import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:5000',
  timeout: 600000, // 延长到600秒，适应AI助手的响应时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 强制禁用测试模式，确保使用真实API
localStorage.removeItem('testMode')

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    const isTestMode = localStorage.getItem('testMode') === 'true'
    
    if (token && !isTestMode) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    const { code, message, data } = response.data
    
    if (code === 200) {
      return data
    } else {
      ElMessage.error(message || '请求失败')
      return Promise.reject(new Error(message || '请求失败'))
    }
  },
  (error) => {
    // 检查是否为测试模式
    const isTestMode = localStorage.getItem('testMode') === 'true'
    
    if (isTestMode) {
      // 测试模式下返回模拟数据
      return Promise.resolve(getMockData(error.config.url, error.config.method))
    }
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          // 检查token是否存在
          const token = localStorage.getItem('token')
          if (token) {
            console.log('Token存在但认证失败，可能是token过期或无效')
            ElMessage.error('认证失败，请重新登录')
            localStorage.removeItem('token')
            localStorage.removeItem('user')
            localStorage.removeItem('testMode')
            window.location.href = '/login'
          } else {
            ElMessage.error('未认证，请先登录')
          }
          break
        case 403:
          ElMessage.error('权限不足')
          break
        case 404:
          ElMessage.error('资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(data?.message || '请求失败')
      }
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
    
    return Promise.reject(error)
  }
)

// 获取模拟数据
const getMockData = (url: string, method: string) => {
  if (url?.includes('/problems')) {
    return {
      problems: [
        {
          id: 1,
          title: '两数之和',
          description: '给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出和为目标值 target 的那两个整数，并返回它们的数组下标。',
          type: 'code',
          difficulty: 'easy',
          answer: null,
          test_cases: '[{"input": "[2,7,11,15]\\n9", "output": "[0,1]"}]',
          points: 10,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 2,
          title: '反转字符串',
          description: '编写一个函数，其作用是将输入的字符串反转过来。',
          type: 'code',
          difficulty: 'easy',
          answer: null,
          test_cases: '[{"input": "hello", "output": "olleh"}]',
          points: 10,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 3,
          title: '最大子数组和',
          description: '给定一个整数数组，找到一个具有最大和的连续子数组。',
          type: 'code',
          difficulty: 'medium',
          answer: null,
          test_cases: '[{"input": "[-2,1,-3,4,-1,2,1,-5,4]", "output": "6"}]',
          points: 15,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 4,
          title: '合并两个有序链表',
          description: '将两个升序链表合并为一个新的升序链表。',
          type: 'code',
          difficulty: 'easy',
          answer: null,
          test_cases: '[{"input": "[1,2,4]\\n[1,3,4]", "output": "[1,1,2,3,4,4]"}]',
          points: 10,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 5,
          title: '有效的括号',
          description: '给定一个只包括 \'(\'，\')\'，\'{\'，\'}\'，\'[\'，\']\' 的字符串，判断字符串是否有效。',
          type: 'code',
          difficulty: 'easy',
          answer: null,
          test_cases: '[{"input": "()", "output": "true"}]',
          points: 10,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 6,
          title: '爬楼梯',
          description: '假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。',
          type: 'code',
          difficulty: 'easy',
          answer: null,
          test_cases: '[{"input": "3", "output": "3"}]',
          points: 10,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 7,
          title: '快速排序',
          description: '实现快速排序算法，对给定的整数数组进行升序排序。',
          type: 'code',
          difficulty: 'hard',
          answer: null,
          test_cases: '[{"input": "[64,34,25,12,22,11,90]", "output": "[11,12,22,25,34,64,90]"}]',
          points: 20,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 8,
          title: '链表反转',
          description: '反转一个单链表。',
          type: 'code',
          difficulty: 'medium',
          answer: null,
          test_cases: '[{"input": "[1,2,3,4,5]", "output": "[5,4,3,2,1]"}]',
          points: 15,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 9,
          title: '二叉树遍历',
          description: '实现二叉树的前序、中序、后序遍历。',
          type: 'code',
          difficulty: 'medium',
          answer: null,
          test_cases: '[{"input": "[1,null,2,3]", "output": "[1,2,3]"}]',
          points: 15,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 10,
          title: '最长公共子序列',
          description: '给定两个字符串 text1 和 text2，返回这两个字符串的最长公共子序列的长度。',
          type: 'code',
          difficulty: 'hard',
          answer: null,
          test_cases: '[{"input": "abcde\\nace", "output": "3"}]',
          points: 20,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 11,
          title: '合并两个有序数组',
          description: '给你两个按非递减顺序排列的整数数组 nums1 和 nums2，另有两个整数 m 和 n。',
          type: 'code',
          difficulty: 'easy',
          answer: null,
          test_cases: '[{"input": "[1,2,3,0,0,0]\\n3\\n[2,5,6]\\n3", "output": "[1,2,2,3,5,6]"}]',
          points: 10,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 12,
          title: 'Python生成器',
          description: 'Python中生成器的主要作用是什么？',
          type: 'choice',
          difficulty: 'medium',
          answer: 'A',
          options: '["内存优化", "提高执行速度", "简化代码", "增加安全性"]',
          points: 10,
          time_limit: 60,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 13,
          title: 'Python上下文管理器',
          description: 'Python中with语句的主要用途是什么？',
          type: 'choice',
          difficulty: 'hard',
          answer: 'B',
          options: '["提高性能", "自动资源管理", "简化循环", "错误处理"]',
          points: 15,
          time_limit: 60,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 14,
          title: 'Python多线程',
          description: 'Python中GIL（全局解释器锁）的作用是什么？',
          type: 'choice',
          difficulty: 'medium',
          answer: 'C',
          options: '["提高多线程性能", "防止内存泄漏", "确保线程安全", "简化编程"]',
          points: 10,
          time_limit: 60,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 15,
          title: 'Python虚拟环境',
          description: 'Python虚拟环境的主要作用是什么？',
          type: 'choice',
          difficulty: 'easy',
          answer: 'A',
          options: '["隔离项目依赖", "提高性能", "简化安装", "增加安全性"]',
          points: 5,
          time_limit: 60,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 16,
          title: 'Python包管理',
          description: 'pip是Python的什么工具？',
          type: 'choice',
          difficulty: 'easy',
          answer: 'B',
          options: '["代码编辑器", "包管理器", "调试工具", "测试框架"]',
          points: 5,
          time_limit: 60,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 17,
          title: 'Python基础语法选择题',
          description: '以下哪个是Python中的正确变量命名？',
          type: 'choice',
          difficulty: 'easy',
          answer: 'B',
          options: '["2variable", "my_variable", "class", "def"]',
          points: 10,
          time_limit: 60,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 18,
          title: '数据结构选择题',
          description: '以下哪种数据结构最适合实现栈（Stack）？',
          type: 'choice',
          difficulty: 'medium',
          answer: 'A',
          options: '["数组或链表", "二叉树", "图", "哈希表"]',
          points: 15,
          time_limit: 60,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 19,
          title: 'Python语法填空题',
          description: '在Python中，用于定义函数的关键字是____，用于定义类的关键字是____。',
          type: 'blank',
          difficulty: 'easy',
          answer: 'def,class',
          points: 10,
          time_limit: 60,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 20,
          title: '算法复杂度填空题',
          description: '快速排序的平均时间复杂度是____，最坏时间复杂度是____。',
          type: 'blank',
          difficulty: 'medium',
          answer: 'O(nlogn),O(n²)',
          points: 15,
          time_limit: 60,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 21,
          title: '面向对象编程简答题',
          description: '请简要说明面向对象编程的三大特性（封装、继承、多态）的含义和作用。',
          type: 'short',
          difficulty: 'medium',
          answer: '封装：将数据和操作数据的方法绑定在一起，对外部隐藏实现细节。继承：子类可以继承父类的属性和方法，实现代码重用。多态：同一个接口可以有多种不同的实现方式。',
          points: 20,
          time_limit: 300,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 22,
          title: '算法设计简答题',
          description: '请描述如何使用深度优先搜索（DFS）算法遍历一棵二叉树，并说明其时间复杂度。',
          type: 'short',
          difficulty: 'hard',
          answer: '深度优先搜索遍历二叉树的过程：1. 访问根节点 2. 递归遍历左子树 3. 递归遍历右子树。时间复杂度为O(n)，其中n是树中节点的数量，因为每个节点都会被访问一次。',
          points: 25,
          time_limit: 300,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 23,
          title: '冒泡排序',
          description: '实现冒泡排序算法，对给定的整数数组进行升序排序。',
          type: 'code',
          difficulty: 'medium',
          answer: null,
          test_cases: '[{"input": "[64,34,25,12,22,11,90]", "output": "[11,12,22,25,34,64,90]"}]',
          points: 20,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 24,
          title: '完成二分查找函数',
          description: '请完成以下二分查找函数中的缺失部分。',
          type: 'code',
          difficulty: 'medium',
          answer: 'if arr[mid] == target:\\n    return mid\\nelif arr[mid] > target:\\n    right = mid - 1\\nelse:\\n    left = mid + 1',
          test_cases: '[{"input": "[1,3,5,7,9,11,13,15]\\n7", "output": "3"}]',
          points: 25,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 25,
          title: '完成链表反转函数',
          description: '请完成以下链表反转函数中的缺失部分。',
          type: 'code',
          difficulty: 'hard',
          answer: 'next_node = current.next\\ncurrent.next = prev\\nprev = current\\ncurrent = next_node',
          test_cases: '[{"input": "[1,2,3,4,5]", "output": "[5,4,3,2,1]"}]',
          points: 30,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 26,
          title: '完成数组排序函数',
          description: '请完成以下数组排序函数中的缺失部分。',
          type: 'code',
          difficulty: 'medium',
          answer: 'for i in range(n):\\n    for j in range(0, n-i-1):\\n        if arr[j] > arr[j+1]:\\n            arr[j], arr[j+1] = arr[j+1], arr[j]',
          test_cases: '[{"input": "[64, 34, 25, 12, 22, 11, 90]", "output": "[11, 12, 22, 25, 34, 64, 90]"}]',
          points: 20,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 27,
          title: '完成字符串反转函数',
          description: '请完成以下字符串反转函数中的缺失部分。',
          type: 'code',
          difficulty: 'easy',
          answer: 'result = s[::-1]',
          test_cases: '[{"input": "hello", "output": "olleh"}]',
          points: 15,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 28,
          title: '完成斐波那契数列函数',
          description: '请完成以下斐波那契数列函数中的缺失部分。',
          type: 'code',
          difficulty: 'medium',
          answer: 'result = fibonacci(n-1) + fibonacci(n-2)',
          test_cases: '[{"input": "5", "output": "5"}]',
          points: 20,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 29,
          title: '完成列表去重函数',
          description: '请完成以下列表去重函数中的缺失部分。',
          type: 'code',
          difficulty: 'easy',
          answer: 'result = list(dict.fromkeys(lst))',
          test_cases: '[{"input": "[1, 2, 2, 3, 4, 4, 5]", "output": "[1, 2, 3, 4, 5]"}]',
          points: 15,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        },
        {
          id: 30,
          title: '完成矩阵转置函数',
          description: '请完成以下矩阵转置函数中的缺失部分。',
          type: 'code',
          difficulty: 'hard',
          answer: 'result = [[matrix[j][i] for j in range(rows)] for i in range(cols)]',
          test_cases: '[{"input": "[[1, 2, 3], [4, 5, 6]]", "output": "[[1, 4], [2, 5], [3, 6]]"}]',
          points: 25,
          time_limit: 1000,
          memory_limit: 64,
          language: 'python',
          created_by: 1,
          status: 'active',
          created_at: '2024-01-01T00:00:00'
        }
      ],
      total: 30,
      pages: 1,
      current_page: 1,
      per_page: 30
    }
  }
  
  if (url?.includes('/homeworks')) {
    return [
      {
        id: 1,
        title: '第一次作业',
        description: '基础编程练习',
        problems: [1, 2],
        deadline: '2024-01-15T23:59:59',
        teacher_id: 2,
        created_at: '2024-01-01T00:00:00',
        problem_details: [
          {
            id: 1,
            title: '两数之和',
            description: '给定一个整数数组...',
            type: 'code'
          },
          {
            id: 2,
            title: 'Hello World',
            description: '编写一个程序输出Hello World',
            type: 'code'
          }
        ]
      },
      {
        id: 2,
        title: '第二次作业',
        description: '进阶编程练习',
        problems: [3],
        deadline: '2024-01-20T23:59:59',
        teacher_id: 2,
        created_at: '2024-01-01T00:00:00',
        problem_details: [
          {
            id: 3,
            title: '选择题示例',
            description: '以下哪个是Python的内置数据类型？',
            type: 'choice'
          }
        ]
      }
    ]
  }
  
  if (url?.includes('/submissions')) {
    return [
      {
        id: 1,
        homework_id: 1,
        problem_id: 1,
        student_id: 3,
        code: 'def twoSum(nums, target):\n    for i in range(len(nums)):\n        for j in range(i+1, len(nums)):\n            if nums[i] + nums[j] == target:\n                return [i, j]\n    return []',
        status: 'AC',
        submit_time: '2024-01-01T00:00:00',
        problem: {
          id: 1,
          title: '两数之和',
          description: '给定一个整数数组...',
          type: 'code'
        },
        homework: {
          id: 1,
          title: '第一次作业',
          description: '基础编程练习'
        },
        student: {
          id: 3,
          username: 'student1',
          role: 'student'
        }
      },
      {
        id: 2,
        homework_id: 1,
        problem_id: 2,
        student_id: 3,
        code: 'print("Hello World")',
        status: 'AC',
        submit_time: '2024-01-01T00:00:00',
        problem: {
          id: 2,
          title: 'Hello World',
          description: '编写一个程序输出Hello World',
          type: 'code'
        },
        homework: {
          id: 1,
          title: '第一次作业',
          description: '基础编程练习'
        },
        student: {
          id: 3,
          username: 'student1',
          role: 'student'
        }
      }
    ]
  }
  
  if (url?.includes('/assistant/chat')) {
    return {
      response: `测试模式AI助手回复：我收到了你的消息。这是一个模拟的AI助手回复，用于测试聊天功能。在实际环境中，这里会显示真实的AI回复内容。`,
      success: true
    }
  }
  
  // 默认返回空数组
  return []
}

export default api
